<template>
  <div class="order-list">
    <h2 class="page-title">Order Management</h2>

    <!-- Search and Filter -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="Order Status">
          <el-select v-model="searchForm.status" placeholder="Select status" clearable style="width: 150px">
            <el-option label="Pending" value="Pending" />
            <el-option label="Paid" value="Paid" />
            <el-option label="Shipped" value="Shipped" />
            <el-option label="Completed" value="Completed" />
            <el-option label="Cancelled" value="Cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            Search
          </el-button>
          <el-button @click="handleReset">Reset</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- Action Bar -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>Order List</span>
          <el-button type="primary" @click="handleCreate">
            <el-icon><Plus /></el-icon>
            Create Order
          </el-button>
        </div>
      </template>

      <!-- Table -->
      <el-table
        v-loading="loading"
        :data="orderList"
        style="width: 100%"
      >
        <el-table-column prop="order_id" label="Order ID" width="80" />
        <el-table-column prop="recipient_name" label="Recipient" width="120" />
        <el-table-column prop="vial_count" label="Vial Qty" width="100" />
        <el-table-column prop="clinic_name" label="Clinic" width="160" show-overflow-tooltip />
        <el-table-column prop="order_date" label="Order Date" width="120">
          <template #default="{ row }">
            {{ formatDate(row.order_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="total_price" label="Total Price" width="120">
          <template #default="{ row }">
            ${{ (Number(row.total_price) || 0).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="Status" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="280">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewDetail(row)">
              Details
            </el-button>
            <el-button
              v-if="row.status === 'Pending'"
              type="success"
              link
              @click="handleUpdateStatus(row, 'Paid')"
            >
              Pay
            </el-button>
            <el-button
              v-if="row.status === 'Paid'"
              type="warning"
              link
              @click="handleUpdateStatus(row, 'Shipped')"
            >
              Ship
            </el-button>
            <el-button
              v-if="row.status === 'Shipped'"
              type="success"
              link
              @click="handleUpdateStatus(row, 'Completed')"
            >
              Complete
            </el-button>
            <el-button
              v-if="row.status !== 'Cancelled' && row.status !== 'Completed'"
              type="danger"
              link
              @click="handleCancel(row)"
            >
              Cancel
            </el-button>
            <!-- Offspring tracking for completed orders -->
            <el-button
              v-if="row.status === 'Completed' && !row.has_offspring"
              type="primary"
              link
              @click="handleAddOffspring(row)"
            >
              + Offspring
            </el-button>
            <el-button
              v-if="row.status === 'Completed' && row.has_offspring"
              type="info"
              link
              disabled
            >
              ✓ Offspring
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePageChange"
        @current-change="handlePageChange"
        style="margin-top: 20px; justify-content: flex-end;"
      />
    </el-card>

    <!-- Order Details Dialog -->
    <el-dialog
      v-model="detailDialogVisible"
      title="Order Details"
      width="700px"
    >
      <div v-if="currentOrder" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="Order ID">
            {{ currentOrder.order_id }}
          </el-descriptions-item>
          <el-descriptions-item label="Order Status">
            <el-tag :type="getStatusType(currentOrder.status)">
              {{ currentOrder.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="Recipient">
            {{ currentOrder.recipient_name }}
          </el-descriptions-item>
          <el-descriptions-item label="Clinic">
            {{ currentOrder.clinic_name || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="Order Date">
            {{ formatDateTime(currentOrder.order_date) }}
          </el-descriptions-item>
          <el-descriptions-item label="Total Price">
            ${{ (Number(currentOrder.total_price) || 0).toFixed(2) }}
          </el-descriptions-item>
          <el-descriptions-item label="Vial Quantity" :span="2">
            {{ currentOrder.vial_count }} vial(s)
          </el-descriptions-item>
        </el-descriptions>

        <div v-if="orderItems.length > 0" style="margin-top: 20px;">
          <h4>Order Items</h4>
          <el-table :data="orderItems" border style="width: 100%; margin-top: 10px;">
            <el-table-column prop="vial_id" label="Vial ID" width="100" />
            <el-table-column prop="donor_code" label="Donor Code" width="150" />
            <el-table-column prop="collection_date" label="Collection Date" width="120">
              <template #default="{ row }">
                {{ formatDate(row.collection_date) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="Status" />
          </el-table>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">Close</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import { orderAPI } from '@/api'

const router = useRouter()

// Search form
const searchForm = reactive({
  status: ''
})

// Pagination
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// Data list
const orderList = ref([])
const loading = ref(false)

// Order details
const detailDialogVisible = ref(false)
const currentOrder = ref(null)
const orderItems = ref([])

// Load list data
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const data = await orderAPI.getList(params)
    orderList.value = data.data || []
    pagination.total = data.count || 0
  } catch (error) {
    ElMessage.error('Failed to load data')
  } finally {
    loading.value = false
  }
}

// Search
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// Page change (do not reset page number)
const handlePageChange = () => {
  loadData()
}

// Reset
const handleReset = () => {
  Object.assign(searchForm, {
    status: ''
  })
  handleSearch()
}

// Create order
const handleCreate = () => {
  router.push('/orders/create')
}

// View details
const handleViewDetail = async (row) => {
  try {
    const data = await orderAPI.getDetail(row.order_id)
    currentOrder.value = data.data
    orderItems.value = data.data.items || []
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('Failed to load order details')
  }
}

// Update order status
const handleUpdateStatus = async (row, newStatus) => {
  try {
    await ElMessageBox.confirm(
      `Are you sure you want to update order status to "${newStatus}"?`,
      'Confirm',
      {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }
    )
    await orderAPI.updateStatus(row.order_id, { status: newStatus })
    ElMessage.success('Status updated successfully')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('Failed to update status')
    }
  }
}

// Cancel order
const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm(
      'Are you sure you want to cancel this order? This action cannot be undone!',
      'Warning',
      {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }
    )
    await orderAPI.updateStatus(row.order_id, { status: 'Cancelled' })
    ElMessage.success('Order cancelled')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('Failed to cancel order')
    }
  }
}

// Add offspring record (only for completed orders)
const handleAddOffspring = (row) => {
  console.log('Order data:', row)
  console.log('Donor ID:', row.donor_id)
  console.log('Recipient ID:', row.recipient_id)
  
  // Get donor ID and recipient ID directly from order list data
  router.push({
    path: '/offspring',
    query: {
      action: 'add',
      orderId: row.order_id,
      donorId: row.donor_id,           // Get directly from list data
      recipientId: row.recipient_id,
      recipientName: row.recipient_name
    }
  })
}

// Format date
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('en-US')
}

// Format date time
const formatDateTime = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('en-US')
}

// Get status type
const getStatusType = (status) => {
  const typeMap = {
    'Pending': 'warning',      // Pending - orange
    'Paid': 'primary',         // Paid - blue
    'Shipped': 'success',      // Shipped - green
    'Completed': 'info',       // Completed - gray
    'Cancelled': 'danger'      // Cancelled - red
  }
  return typeMap[status] || ''
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.order-list {
  padding: 0;
}

.page-title {
  font-size: 24px;
  font-weight: 500;
  margin-bottom: 20px;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-detail {
  padding: 10px 0;
}

.order-detail h4 {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: 500;
}
</style>
